package is.ru.honn.rupin.data;

import is.ru.honn.rupin.domain.User;
import is.ruframework.data.RuData;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Sigrún Inga Kristinsdóttir.
 * Date: 18.10.2012
 * Time: 14:55
 * copyright (c) sigruninga&susanne
 *
 * @author Sigrún Inga kristindóttir og Susanne Götz
 * @version 1.1
 */

/**
 * Gangnagrunstenging fyrir Notendur.
 */
public class UserData extends RuData implements UserDataGateway
{
    /**
     * Fall sem skráir upplýsingar um notanda í gagnagrunn.
     * @param user
     * @return int sem er id notanda
     */
    public int add(User user)
    {
        SimpleJdbcInsert insertUser = new SimpleJdbcInsert(getDataSource()).withTableName("ru_users").usingGeneratedKeyColumns("id");

        Map<String, Object> parameters = new HashMap<String, Object>(6);
        parameters.put("username", user.getUsername());
        parameters.put("firstName", user.getFirstName());
        parameters.put("lastName", user.getLastName());
        parameters.put("email", user.getEmail());
        parameters.put("passw", user.getPassword());
        parameters.put("gender", user.getGender());
        int returnKey = 0;

        try
        {
            returnKey = insertUser.executeAndReturnKey(parameters).intValue();
        }
        catch (DataIntegrityViolationException divex)
        {
            log.warning("Duplicate entry");
            return 0;                             // enginn id returned því enginn skráning átti sér stað
        }
        return returnKey;
    }

    /**
     * Fall sem sækir notanda með notendanafn "username" úr gagnagrunni
     * @param username
     * @return User með gefin username eða null ef engin notanda með þessu notandanafni fannst.
     */
    public User getUserByUsername(String username)
    {
       JdbcTemplate queryContent = new JdbcTemplate(getDataSource());
       String sql = "select * from ru_users where username = ?";
       User user;
        // til að hafa möguleika að skila null ef engin notandi tengd þessu notendanafni finnst
        // því queryForObject þarf að skila eintaki af User, annars hættir keyrslan
       try
       {
            user = queryContent.queryForObject(sql, new Object[] { username }, new UserRowMapper());
       }
       catch (EmptyResultDataAccessException e)
       {
           //System.out.println("No user found");
           return null;
       }

       return user;
    }
}

